<template>
  <div class="import-c">
    <input ref="file" id="file" style="display: none" @change="fileChange" type="file">
    <div class="imei-text">
      <el-input class="imei-input" resize="none" :autosize="{ minRows: 19 }" type="textarea" :placeholder="$t('请输入内容')"
        @input="countRepeatOrderNum" v-model="imeis">
      </el-input>
    </div>
    <div class="import-right">
      <div class="op-button-c">
        <div>
          <el-button class="op-button chose-file" @click="improtImeis">{{ $t('选择文件') }}</el-button>
        </div>
        <div>
          <el-button class="op-button chose-file" @click="clearImeis">{{ $t('清空内容') }}</el-button>
        </div>
        <div>
          <el-button class="op-button chose-file" @click="analisyImei">{{ $t('解析数据') }}</el-button>
        </div>
      </div>
      <!--            <div class="remark-c">-->
      <!--                <span>备注:</span>-->
      <!--                <el-input-->
      <!--                        resize="none"-->
      <!--                        rows="10"-->
      <!--                        type="textarea"-->
      <!--                        placeholder="请输入备注"-->
      <!--                        v-model="remark"-->
      <!--                        maxlength="30"-->
      <!--                        show-word-limit-->
      <!--                >-->
      <!--                </el-input>-->
      <!--            </div>-->
      <div class="tip-container">
        <div class="tip">
          <div>{{ $t('提示：') }}</div>
          <span>{{ $t('1、当前余额可以提交订单数量:') }}<span style="color: red">{{ availableOrderNum }}</span>{{ $t('个')
            }}</span><br>
          <span>{{ $t('2、当前订单数:') }}<span style="color: red">{{ orderNum }}</span>{{ $t('个') }}</span><br>
          <span>{{ $t('3、重复订单有:') }}<span style="color: red">{{ repeatOrderNum }}</span>{{ $t('个') }}</span><br>
          <span>{{ $t('4、重复订单会自动去重') }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as util from '@/utils/index'
export default {
  props: {
    availableOrderNum: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      remark: '',
      imeis: '',
      tableData: [],
      file: {
        value: null,
      },
      repeatOrderNum: 0,
      orderNum: 0
    }
  },
  methods: {
    clearImeis() {
      this.imeis = ''
      this.tableData = []
    },
    //导入imeis
    improtImeis() {
      var input = document.createElement("input");
      input.type = "file"; // 设置input类型为button
      input.onchange = this.fileChange
      input.click()
      input.remove()
    },
    fileChange(e) {
      let file = e.target.files[0]
      try {
        this.analisyFile(file)
      } catch (e) {
        file.value = ''
      } finally {
        file.value = ''
      }
      file.value = ''
    },
    analisyImei() {
      // 正则表达式用于匹配15位或16位的纯数字IMEI
      const imeiRegex = /^[\d]{15}(?:[\d]{2})?$/;
      let imeiList = this.imeis.replace(/[^\d,\n,,,，,\s]/g, '').split(/\n|\t|\r|,|，|\s/)
      imeiList = imeiList.map(x => x.match(imeiRegex)?.[0]?.trim()).filter(x => util.isValidIMEI(x))
      imeiList.forEach(imei => {
        if (!this.tableData.map(x => x.imei).includes(imei)) {
          this.tableData.push({
            imei: imei.toString().replace(/[\s\n\t]/g, ''),
            state: this.$t('已导入'),
            remark: this.remark
          })
        }
      })

      console.log(this.tableData)

      this.$emit('analisyImei', this.tableData)
      this.$emit('closeImport')
      this.imeis = ''
      this.tableData = []
    },
    analisyFile(file) {
      if (!file) {
        return;
      }
      if (file.type === 'text/plain') {
        const reader = new FileReader(); // 创建FileReader对象
        reader.onload = e => {
          const content = e.target.result; // 获取文件内容
          // 对内容进行解析，例如按行分割
          this.imeis = this.imeis + content + '\n'
        };

        reader.onerror = function (e) {
          console.error('File could not be read! Code: ' + e.target.error.code);
        };

        reader.readAsText(file); // 以文本格式读取文件
      }

      if (file.type.endsWith('.sheet')) {
        const XLSX = require('xlsx');
        const reader = new FileReader();
        reader.onload = e => {
          const data = new Uint8Array(e.target.result);
          const workbook = XLSX.read(data, { type: 'array' });
          const firstSheetName = workbook.SheetNames[0];
          const worksheet = workbook.Sheets[firstSheetName];
          const lines = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

          lines.forEach(line => {
            this.imeis = this.imeis + line + '\n'
          })
        };
        reader.readAsArrayBuffer(file);
      }
    },
    countRepeatOrderNum() {
      const imeiList = this.imeis.split(/\n|\t|\r/)
      const availableImeiList = imeiList.filter(x => util.isValidIMEI(x))
      const distinctOrders = Array.from(new Set(availableImeiList));
      this.orderNum = availableImeiList.length
      this.repeatOrderNum = availableImeiList.length - distinctOrders.length
    }
  }
}
</script>

<style>
.import-c {
  width: 100%;
  height: 500px;
  display: flex;
  gap: 20px;
}

.imei-input {
  font-size: 16px;
  overflow: scroll;
  max-height: 100%;
}


.imei-text {
  flex-grow: 3;
  height: 100%;
}

.import-right {
  flex-grow: 7;
  text-align: left;
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.op-button-c {}


.remark-c {
  flex-grow: 5;
}

.tip-container {
  width: 100%;
  flex-grow: 3;
  position: relative;
}

.tip {
  color: #1A79FF;
  width: fit-content;
  position: absolute;
  bottom: 20px;
}

.op-button {
  width: fit-content;
}
</style>